package com.mlnx.sim.ecg.client;

import com.mlnx.common.utils.MyLog;
import com.mlnx.mptp.mptp.MpPacket;
import com.mlnx.tp.base.utils.LogUtils;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;

/**
 * @author fzh
 * @create 2018/3/26 16:21
 */
public class MpClientBootstrap {

    MyLog log = MyLog.getLog(getClass());

    private int port;
    private String host;
    public SocketChannel socketChannel;
    private MpClientLis mpClientLis;

    public MpClientBootstrap(int port, String host, MpClientLis mpClientLis) {
        this.port = port;
        this.host = host;
        this.mpClientLis = mpClientLis;
        start();
    }

    private void start() {
        ChannelFuture future = null;
        try {
            EventLoopGroup eventLoopGroup = new NioEventLoopGroup();
            Bootstrap bootstrap = new Bootstrap();
            bootstrap.channel(NioSocketChannel.class);
            bootstrap.option(ChannelOption.SO_KEEPALIVE, true);
            bootstrap.group(eventLoopGroup);
            bootstrap.remoteAddress(host, port);
            bootstrap.handler(new TcpClientInitializer(mpClientLis));
            future = bootstrap.connect(host, port).sync();
            if (future.isSuccess()) {
                socketChannel = (SocketChannel) future.channel();
                LogUtils.i("connect server  成功---------");
            } else {
                LogUtils.e("连接失败！");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void send(MpPacket mpPacket) {

        try {
            if (socketChannel == null || !socketChannel.isActive()) {
                log.error("未连接，先等待连接服务器");
                start();
            }
            socketChannel.writeAndFlush(mpPacket);
        }catch (Exception e){
            log.error(e, "发送数据失败");
            if (socketChannel != null){
                socketChannel.close();
                socketChannel = null;
            }
        }
    }
}
